package middleware

import (
	"n-server/pkg/common/errorcode"
	"n-server/pkg/common/response"
	"time"

	"github.com/gin-gonic/gin"
	"golang.org/x/time/rate"
)

// RateLimit 限流中间件
func RateLimit() gin.HandlerFunc {
	limiter := rate.NewLimiter(rate.Every(time.Second), 100) // 每秒 100 个请求

	return func(c *gin.Context) {
		if !limiter.Allow() {
			response.ErrorMsg(c, errorcode.SYSTEM_ERROR, "Rate limit exceeded")
			c.Abort()
			return
		}
		c.Next()
	}
}